package com.example.hospitalManage.service.impl;

import com.example.hospitalManage.common.HospitalManageException;
import com.example.hospitalManage.common.ServiceResultEnum;
import com.example.hospitalManage.controller.user.param.UserUpdateParam;
import com.example.hospitalManage.dao.UserOperateMapper;
import com.example.hospitalManage.dao.UserOperateTokenMapper;
import com.example.hospitalManage.entity.UserInfo;
import com.example.hospitalManage.entity.UserToken;
import com.example.hospitalManage.service.UserOperateService;
import com.example.hospitalManage.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @ProjectName: yygh
 * @Author: gxy
 * @Time: 2022/12/29 20:18
 * @Description: 描述
 */
@Service
public class UserOperateServiceImpl implements UserOperateService {

    @Autowired
    private UserOperateMapper userOperateMapper;

    @Autowired
    private UserOperateTokenMapper userOperateTokenMapper;

    @Override
    public String register(String nickName, String password, String phone, String name) {
        if (userOperateMapper.selectByName(name) != null) {
            return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult();
        }
        UserInfo registerUser = new UserInfo();
        registerUser.setName(name);
        registerUser.setNickName(nickName);
        registerUser.setStatus(1);
        registerUser.setPhone(phone);
        String passwordMD5 = MD5Util.MD5Encode(password, "UTF-8");
        registerUser.setPassword(passwordMD5);
        if (userOperateMapper.insertSelective(registerUser) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String login(String phone, String password) {

        UserInfo user = userOperateMapper.selectByPhoneAndPasswd(phone, password);
        if (user != null) {
            if (user.getStatus() == 0) {
                return ServiceResultEnum.LOGIN_USER_LOCKED_ERROR.getResult();
            }
            //登录后即执行修改token的操作
            String token = getNewToken(System.currentTimeMillis() + "", user.getId());
            UserToken userToken = userOperateTokenMapper.selectByPrimaryKey(user.getId());
            //当前时间
            Date now = new Date();
            //过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);//过期时间 48 小时
            if (userToken == null) {
                userToken = new UserToken();
                userToken.setUserId(user.getId());
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //新增一条token数据
                if (userOperateTokenMapper.insertSelective(userToken) > 0) {
                    //新增成功后返回
                    return token;
                }
            } else {
                userToken.setToken(token);
                userToken.setUpdateTime(now);
                userToken.setExpireTime(expireTime);
                //更新
                if (userOperateTokenMapper.updateByPrimaryKeySelective(userToken) > 0) {
                    //修改成功后返回
                    return token;
                }
            }

        }
        return ServiceResultEnum.LOGIN_ERROR.getResult();
    }

    /**
     * 获取token值
     *
     * @param timeStr
     * @param userId
     * @return
     */
    private String getNewToken(String timeStr, Long userId) {
        String src = timeStr + userId + NumberUtil.genRandomNum(4);
        return SystemUtil.genToken(src);
    }


    @Override
    public Boolean updateUserInfo(Long userId, UserUpdateParam userInfo) {
        UserInfo user = userOperateMapper.selectByPrimaryKey(userId);
        if (user == null) {
            HospitalManageException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        user.setNickName(userInfo.getNickName());
        user.setPhone(userInfo.getPhone());
        user.setCertificatesNo(userInfo.getCertificatesNo());
        user.setCertificatesType(userInfo.getCertificatesType());
        user.setCertificatesUrl(userInfo.getCertificatesUrl());
        //若密码为空字符，则表明用户不打算修改密码，使用原密码保存
        if (!MD5Util.MD5Encode("", "UTF-8").equals(userInfo.getPasswordMd5())){
            user.setPassword(userInfo.getPasswordMd5());
        }

        if (userOperateMapper.updateByPrimaryKeySelective(user) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean logout(Long userId) {
        return userOperateTokenMapper.deleteByPrimaryKey(userId) > 0;
    }

    @Override
    public Boolean lockUsers(Long[] ids, int status) {
        if (ids.length < 1) {
            return false;
        }
        return userOperateMapper.lockUserBatch(ids, status) > 0;
    }


    @Override
    public PageResult getUsersPage(PageQueryUtil pageUtil) {
        List<UserInfo> userInfo = userOperateMapper.findMallUserList(pageUtil);
        int total = userOperateMapper.getTotalUsers(pageUtil);
        PageResult pageResult = new PageResult(userInfo, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }



}
